<template>
  <div class="order-manage">
    <h1 class="page-title">订单管理</h1>

    <el-table :data="orders" style="width: 100%">
      <el-table-column prop="id" label="订单ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column label="商品" width="200">
        <template #default="{ row }">
          <div v-for="item in row.items" :key="item.productId">
            {{ item.name }} x {{ item.quantity }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="收货信息" width="250">
        <template #default="{ row }">
          <div>{{ row.shippingAddress.name }}</div>
          <div>{{ row.shippingAddress.phone }}</div>
          <div>{{ row.shippingAddress.address }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice" label="总价" width="100">
        <template #default="{ row }">
          ¥{{ row.totalPrice }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="下单时间" width="180" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button size="small" @click="viewDetail(row)">查看详情</el-button>
          <el-select v-model="row.status" size="small" @change="updateStatus(row.id, row.status)">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="600px">
      <div v-if="currentOrder">
        <p><strong>订单ID：</strong>{{ currentOrder.id }}</p>
        <p><strong>用户名：</strong>{{ currentOrder.username }}</p>
        <p><strong>下单时间：</strong>{{ currentOrder.createdAt }}</p>

        <h3>商品列表</h3>
        <el-table :data="currentOrder.items">
          <el-table-column prop="name" label="商品名" />
          <el-table-column prop="price" label="单价" />
          <el-table-column prop="quantity" label="数量" />
        </el-table>

        <h3>收货信息</h3>
        <p>姓名：{{ currentOrder.shippingAddress.name }}</p>
        <p>电话：{{ currentOrder.shippingAddress.phone }}</p>
        <p>地址：{{ currentOrder.shippingAddress.province }} {{ currentOrder.shippingAddress.city }} {{ currentOrder.shippingAddress.address }}</p>

        <p><strong>总价：</strong>¥{{ currentOrder.totalPrice }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()
const orders = ref([])
const detailVisible = ref(false)
const currentOrder = ref(null)

const fetchOrders = async () => {
  try {
    const token = localStorage.getItem('token')
    
    // 检查token是否存在
    if (!token) {
      ElMessage.error('未登录，请先登录')
      router.push('/login')
      return
    }

    console.log('使用的Token:', token) // 调试用
    
    // 从服务器获取订单（两个项目共用3002端口，所以只需要调用一次）
    const response = await axios.get('/api/admin/orders', {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
    
    if (response.data && response.data.success) {
      orders.value = response.data.data || []
      // 按创建时间倒序排序
      orders.value.sort((a, b) => {
        const timeA = new Date(a.createdAt || 0).getTime()
        const timeB = new Date(b.createdAt || 0).getTime()
        return timeB - timeA
      })
    }
    
    console.log('订单API响应 - 订单数量:', orders.value.length)
    console.log('订单详情:', orders.value)
    
    if (orders.value.length === 0) {
      ElMessage.info('暂无订单数据')
    } else {
      ElMessage.success(`成功加载 ${orders.value.length} 个订单`)
    }
  } catch (error) {
    console.error('获取订单失败详情:', error) // 调试用
    
    // 显示详细错误信息
    if (error.response) {
      const status = error.response.status
      const message = error.response.data?.message || '请求失败'
      
      if (status === 401) {
        ElMessage.error('未授权，请使用管理员账号重新登录')
        // 清除token，跳转登录
        localStorage.removeItem('token')
        localStorage.removeItem('user')
        authStore.isLoggedIn = false
        router.push('/login')
      } else if (status === 403) {
        ElMessage.error('无权限访问，需要管理员权限')
      } else {
        ElMessage.error(`获取订单列表失败: ${message} (${status})`)
      }
    } else if (error.request) {
      ElMessage.error('网络错误，无法连接到服务器，请确认后端服务已启动')
    } else {
      ElMessage.error('请求失败: ' + error.message)
    }
  }
}

const updateStatus = async (orderId, status) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    // 更新订单状态（两个项目共用3002端口，所以只需要更新一次）
    const response = await axios.put(`/api/admin/orders/${orderId}/status`,
        { status },
        {
          headers: {
            Authorization: `Bearer ${token}`
          }
        }
    )
    
    if (response.data && response.data.success) {
      ElMessage.success('订单状态更新成功')
      fetchOrders() // 重新获取订单列表
    } else {
      ElMessage.error(response.data?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
    if (error.response?.status === 401 || error.response?.status === 403) {
      ElMessage.error('权限不足，请重新登录')
      router.push('/login')
    } else {
      ElMessage.error(error.response?.data?.message || '更新失败')
    }
  }
}

const viewDetail = (order) => {
  currentOrder.value = order
  detailVisible.value = true
}

const getStatusText = (status) => {
  const map = {
    pending: '待处理',
    processing: '处理中',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

const getStatusType = (status) => {
  const map = {
    pending: 'warning',
    processing: 'info',
    shipped: '',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.order-manage {
  padding: 0;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #303133;
}
</style>